package com.twu.biblioteca;

import java.util.LinkedHashMap;
import java.util.Map;

public class Library {
    private Map<String, Item> bookMap;
    private Map<String, Item> movieMap;

    public Library() {
        bookMap = new LinkedHashMap<String, Item>();
        movieMap = new LinkedHashMap<String, Item>();
    }

    public void addBook(Book book) {
        addItem(bookMap, book);
    }

    public void addMovie(Movie movie) {
        addItem(movieMap, movie);
    }

    public String displayAvailableBookList() {
        return displayAvailableItemList(bookMap, "Title | Author | Year");
    }

    public String displayAvailableMovieList() {
        return displayAvailableItemList(movieMap, "Title | Director | Rating | Year");
    }

    public boolean checkoutBookByTitle(String title) {
        return checkoutItemByTitle(bookMap, title);
    }

    public boolean checkoutMovieByTitle(String title) {
        return checkoutItemByTitle(movieMap, title);
    }

    public boolean returnBookByTitle(String title) {
        Item item = bookMap.get(title);
        return item != null && item.returnItem();
    }

    private void addItem(Map<String, Item> map, Item item) {
        map.put(item.displayTitle(), item);
    }

    private String displayAvailableItemList(Map<String, Item> map, String header) {
        StringBuilder itemListBuilder = new StringBuilder();
        itemListBuilder.append(header);
        for(Item item : map.values()) {
            if(!item.isCheckedOut()) {
                itemListBuilder.append(System.lineSeparator());
                itemListBuilder.append(item.displayDetails());
            }
        }
        return itemListBuilder.toString();
    }

    private boolean checkoutItemByTitle(Map<String, Item> map, String title) {
        Item item = map.get(title);
        return item != null && item.checkout();
    }
}